package edu.mju.user.controller;


import edu.mju.serviceutils.MD5Util;
import edu.mju.serviceutils.ResponseCode;
import edu.mju.serviceutils.StrUtil;
import edu.mju.user.entity.User;
import edu.mju.user.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author CBL
 * @since 2020-12-31
 */
@RestController
@RequestMapping("/user/user")
@CrossOrigin
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @PostMapping("/login")
    public ResponseCode login(@RequestBody User user){
        //取出数据库中的数据
        User getuser = userService.getByUserName(user);
        if(ObjectUtils.isNotEmpty(user)&&ObjectUtils.isNotEmpty(getuser)){
            String salt = getuser.getSalt();
            String md5Password = MD5Util.md5(user.getPassword()+salt);
            if(getuser.getPassword().equals(md5Password)){
                //return ResponseCode.success().message("登录成功！").data("userId",getuser.getId()).data("status",getuser.getStatus()).data("token","admin");
                return ResponseCode.success().data("token","admin");
            }
        }

        return ResponseCode.error().message("登录失败！");
    }

    @GetMapping("/info")
    public ResponseCode info(){
        return ResponseCode.success().data("roles","[admin]").data("name","admincbl").data("avatar","https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1591570509,3992175704&fm=26&gp=0.jpg");
    }

    @PostMapping("/register")
    public ResponseCode register(@RequestBody User user){
        user.setSalt(StrUtil.randString(32));
        user.setPassword(MD5Util.md5(user.getPassword()+user.getSalt()));
        boolean b = userService.saveOrUpdate(user);
        if(b){
            return ResponseCode.success().message("注册成功！");
        }
        return ResponseCode.error().message("注册失败！");
    }


}

